package com.chidopi.market.aa.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.chidopi.market.aa.dao.IPasswordDao;
import com.chidopi.market.aa.domain.Accounts;
import com.chidopi.market.aa.service.IPasswordService;
import com.chidopi.market.aa.service.IPermissionService;
import com.chidopi.market.util.PasswordEncoder;

public class PasswordServiceImpl implements IPasswordService {

	@Autowired
	@Qualifier("passwordDao")
	private IPasswordDao passwordDao;
	
	@Autowired
	@Qualifier("permissionService")
	private IPermissionService permissionService;
	
	@Override
	public Accounts findById(Object id) throws Exception {
		return passwordDao.findById(id);
	}

	@Override
	public void changePassword(Accounts account) throws Exception {
				
		String pass = PasswordEncoder.encode(account.getPassword(),account.getUsername());
		account.setPassword(pass);
		int ret = passwordDao.update(account);
		if(ret == 1){
			 Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
			 SecurityContextHolder.getContext().setAuthentication(createNewAuthentication(currentUser, pass));
		}
	}

	protected Authentication createNewAuthentication(
			Authentication currentAuth, String newPassword)throws Exception {
		UserDetails user = permissionService.loadUserByUsername(currentAuth.getName());
		UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
				user, user.getPassword(), user.getAuthorities());
		newAuthentication.setDetails(currentAuth.getDetails());

		return newAuthentication;
	}
}
